/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file   fatfs.c
 * @brief  Code for fatfs applications
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
#include "fatfs.h"

uint8_t retUSER;    /* Return value for USER */
char USERPath[4];   /* USER logical drive path */
FATFS USERFatFS;    /* File system object for USER logical drive */
FIL USERFile;       /* File object for USER */

/* USER CODE BEGIN Variables */
FRESULT fresult;
FIL *ffp = &USERFile;
/* USER CODE END Variables */

void MX_FATFS_Init(void)
{
  /*## FatFS: Link the USER driver ###########################*/
  retUSER = FATFS_LinkDriver(&USER_Driver, USERPath);

  /* USER CODE BEGIN Init */
  /* additional user code for init */

  fresult = f_mount(&USERFatFS, USERPath, 1);
  fresult = f_open(&USERFile, "0:/magic.txt", FA_OPEN_EXISTING | FA_READ);
  if (fresult != FR_OK)
  {
    //fresult = f_mount(&USERFatFS, USERPath, 1);
    fresult = f_mkfs(USERPath, 0, 0);
    fresult = f_open(&USERFile, "0:/magic.txt", FA_CREATE_ALWAYS | FA_READ | FA_WRITE);
    UINT bw = 0;
    fresult = f_write(&USERFile, "123456789", 10, &bw);
    if (fresult == FR_OK && bw == 10)
    {
      f_lseek(&USERFile, 0);
      char read_buf[10] = {0};
      UINT br = 0;
      fresult = f_read(&USERFile, read_buf, 10, &br);

      uart_printf("magic:%s\n", read_buf);
    }
  }
  fresult = f_close(&USERFile);

  /* USER CODE END Init */
}

/**
  * @brief  Gets Time from RTC
  * @param  None
  * @retval Time in DWORD
  */
DWORD get_fattime(void)
{
  /* USER CODE BEGIN get_fattime */
  return 0;
  /* USER CODE END get_fattime */
}

/* USER CODE BEGIN Application */

/* USER CODE END Application */
